package cpu.footprint.ui;

import android.app.Dialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Handler;
import android.support.v4.widget.DrawerLayout;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.squareup.picasso.Picasso;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import cpu.footprint.R;
import cpu.footprint.api.ApiUrl;
import cpu.footprint.api.AppXUtilDao;
import cpu.footprint.api.LocalStorage;
import cpu.footprint.api.MyApplication;
import cpu.footprint.api.ResultMessage;
import cpu.footprint.bean.BaseBean;
import cpu.footprint.bean.User;
import cpu.footprint.common.BaseActivity;
import cpu.footprint.api.APIService;
import cpu.footprint.api.RespCallBack;
import cpu.footprint.popup.ExitPopupWindow;
import cpu.footprint.util.CreateDialogUtil;
import cpu.footprint.util.DensityUtil;
import cpu.footprint.util.FileUtil;

import static cpu.footprint.api.ApiUrl.URL_FILEPATH;

@ContentView(R.layout.activity_main)
public class MainActivity extends BaseActivity {
    @ViewInject(R.id.drawerlayout)
    public DrawerLayout dl;
    @ViewInject(R.id.left)
    public LinearLayout r1Left;//左边侧滑布局
    @ViewInject(R.id.image_head)
    public ImageView image_head;
    @ViewInject(R.id.text_nickName)
    private TextView text_nickName;//昵称
    @ViewInject(R.id.text_individualSignature)
    private TextView text_individualSignature;//个性签名
    @ViewInject(R.id.text_map)
    private TextView text_map;//标题栏地图文字
    @ViewInject(R.id.text_group)
    private TextView text_group;//标题栏群组文字
    @ViewInject(R.id.text_active)
    private TextView text_active;//标题栏活动文字
    @ViewInject(R.id.image_map)
    public ImageView image_map;//标题栏地图图标
    @ViewInject(R.id.image_group)
    public ImageView image_group;//标题栏群组图标
    @ViewInject(R.id.image_active)
    public ImageView image_active;//标题栏活动图标\
    @ViewInject(R.id.otherFrameLayout)
    private FrameLayout otherFrameLayout;//容器
    public static LinearLayout layout_map;
    private FragmentManager fragmentManager;
    private Fragment mFragment = null;//当前Fragment
    private MapFragment mapFragment = null;//当前Fragment
    private Fragment activeFragment = null;//当前Fragment
    private Fragment groupFragment = null;//当前Fragment
    private User user = new User();
    private MyApplication myApplication;
    private AppXUtilDao mAppXUtilDao;
    private String mUserMoblie = "";
    private boolean IMLoginFinsh = false;//Im登录是否成功
    private boolean LocalLoginFinsh = false;//本地登录是否成功
    private Dialog mDialog;
    private float width;
    private ExitPopupWindow exitPopupWindow;//
    private int fragmentId = 0;//碎片Id（0代表活动，1代表群组，3代表地图）
    private Boolean isShowPup = false;// pupwindow是否显示
    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (mDialog != null) {
                if (mDialog.isShowing())
                    mDialog.dismiss();
            }
            switch (msg.what) {
                case ResultMessage.IMLOGIN_SUCCESS: {
                    myApplication.setIsLogin(true);
                    IMLoginFinsh = true;
                    GetLogin();
                }
                break;
                case ResultMessage.IMLOGIN_FAILED: {
                    if (mDialog != null) {
                        if (mDialog.isShowing())
                            mDialog.dismiss();
                    }
                    myApplication.setIsLogin(false);
                    String message = msg.obj.toString();
                    IMLoginFinsh = false;
                    Toast.makeText(getApplicationContext(), "登录失败:" + message,
                            Toast.LENGTH_SHORT).show();
                }
                break;
                case ResultMessage.GET_HEAD_SUCCESS:
                    byte[] binaryData = (byte[]) msg.obj;
                    if (binaryData.length != 0) {
                        Bitmap head = BitmapFactory.decodeByteArray(binaryData, 0, binaryData.length);
                        image_head.setImageBitmap(head);
                        String fileName = URL_FILEPATH + user.getMobilePhone() + ".png";
                        if (head != null)
                            FileUtil.saveMyBitmap(fileName, head);
                        if (FileUtil.fileIsExists(fileName)) {
                            Uri uri = Uri.fromFile(new File(fileName));
                            image_head.setImageURI(uri);
                        }
                        head.recycle();
                    } else {

                    }
                    //updateImage();
                    break;
                case ResultMessage.GET_HEAD_FAILED:
                    CreateDialogUtil.ToastShow(MainActivity.this, msg.obj.toString());
                    break;
                case ResultMessage.FAILED:
                    CreateDialogUtil.ToastShow(MainActivity.this, "连接失败");
                    break;
                case ResultMessage.TIMEOUT:
                    CreateDialogUtil.ToastShow(MainActivity.this, "连接超时");
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        width = DensityUtil.getDisplayWidth(this);
        LinearLayout linearLayout = (LinearLayout) findViewById(R.id.left);
        ViewGroup.LayoutParams layoutParams = linearLayout.getLayoutParams();
        layoutParams.width = (int) ((width * 4) / 5);
        linearLayout.setLayoutParams(layoutParams);
        initView();
        myApplication = (MyApplication) getApplication();
        mAppXUtilDao = new AppXUtilDao();
        if (myApplication.isLogin()) {
            setData();
        } else {
            doGetLocalStorage();
        }
    }

    /**
     * 初始化View
     */
    private void initView() {
        // 关闭手势滑动
        //dl.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
        layout_map= (LinearLayout) findViewById(R.id.layout_map);
        if (dl != null)
            dl.addDrawerListener(new DrawerLayout.DrawerListener() {
                @Override
                public void onDrawerSlide(View drawerView, float slideOffset) {

                }

                @Override
                public void onDrawerOpened(View drawerView) {
                    // 打开手势滑动
                    dl.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
                }

                @Override
                public void onDrawerClosed(View drawerView) {
                    // 关闭手势滑动
                    dl.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
                }

                @Override
                public void onDrawerStateChanged(int newState) {

                }
            });
        fragmentManager = getFragmentManager();
        otherFrameLayout.setVisibility(View.VISIBLE);
        activeFragment = new ActiveFragment();
        mapFragment = new MapFragment();
        groupFragment = new GroupFragment();
        mFragment = activeFragment;
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(R.id.otherFrameLayout, mFragment, "active");
        fragmentId = 0;
        fragmentTransaction.commit();
        mDialog = showLoadingDialog(this);
    }

    /**
     * 点击事件监听
     *
     * @param v
     */
    @Event(value = {R.id.image_head, R.id.text_nickName, R.id.leftnav, R.id.nav_exit, R.id.layout_map, R.id.layout_active, R.id.layout_group, R.id.nav_aboutus, R.id.nav_checkupdate, R.id.nav_myactive, R.id.nav_historyfoot, R.id.nav_setting})
    private void onClick(View v) {
        fragmentManager = getFragmentManager();
        switch (v.getId()) {
            case R.id.nav_exit: {
                if (dl.isDrawerOpen(r1Left)) {
                    dl.closeDrawer(r1Left);
                }
                pupwindowShow();
            }
            break;
            case R.id.leftnav: {

            }
            break;
            case R.id.nav_myactive: {
                if (myApplication.isLogin()) {
                    Intent intent = new Intent(this, MyActiveActivty.class);
                    startActivity(intent);
                    overridePendingTransition(0,R.anim.fade);
                } else {
                    Toast( "请先登录");
                }
            }
            break;
            case R.id.nav_checkupdate: {
                // mFragment = new ToolsFragment();
//                fragmentTransaction.replace(R.id.fragment_layout, mFragment);
//                fragmentTransaction.commit();
//                if (dl.isDrawerOpen(r1Left)) {
//                    dl.closeDrawer(r1Left);
//                }
            }
            break;
            case R.id.image_head: {
                if (myApplication.isLogin()&&myApplication.getUser()!=null) {
                    Intent intent = new Intent(this, PersonInfoActivity.class);
                    startActivityForResult(intent, 11);
                    overridePendingTransition(0,R.anim.fade);
                } else {
                    Toast( "请先登录");
                }
            }
            break;
            case R.id.text_nickName: {
                if (!myApplication.isLogin()) {
                    Intent intent = new Intent(this, LoginActivity.class);
                    startActivity(intent);
                    overridePendingTransition(0,R.anim.fade);
                    this.finish();
                }
            }
            break;
            case R.id.nav_setting: {
//                Intent intent = new Intent(this, SettingActivity.class);
//                startActivityForResult(intent, 1);
            }
            break;
            case R.id.layout_map: {
                if (fragmentId != 2) {
                    fragmentId = 2;
                    switchContent(mFragment, mapFragment);
                    overridePendingTransition(0,R.anim.fade);
                    image_map.setImageResource(R.mipmap.map_click);
                    image_group.setImageResource(R.mipmap.group);
                    image_active.setImageResource(R.mipmap.active);
                    text_active.setTextColor(getResources().getColor(R.color.colorblack));
                    text_map.setTextColor(getResources().getColor(R.color.colorLightBlue));
                    text_group.setTextColor(getResources().getColor(R.color.colorblack));
                }
            }
            break;
            case R.id.layout_group: {
                if (fragmentId != 1) {
                    fragmentId = 1;
                    switchContent(mFragment, groupFragment);
                    image_map.setImageResource(R.mipmap.map);
                    image_group.setImageResource(R.mipmap.group_click);
                    image_active.setImageResource(R.mipmap.active);
                    overridePendingTransition(0,R.anim.fade);
                    text_active.setTextColor(getResources().getColor(R.color.colorblack));
                    text_map.setTextColor(getResources().getColorStateList(R.color.colorblack));
                    text_group.setTextColor(getResources().getColor(R.color.colorLightBlue));
                }
            }
            break;
            case R.id.layout_active: {
                if (fragmentId != 0) {
                    fragmentId = 0;
                    switchContent(mFragment, activeFragment);
                    image_map.setImageResource(R.mipmap.map);
                    image_group.setImageResource(R.mipmap.group);
                    image_active.setImageResource(R.mipmap.active_click);
                    text_active.setTextColor(getResources().getColor(R.color.colorLightBlue));
                    text_map.setTextColor(getResources().getColorStateList(R.color.colorblack));
                    text_group.setTextColor(getResources().getColorStateList(R.color.colorblack));
                }
            }
            break;
        }
    }

    /**
     * 切换侧滑栏的状态
     */
    public void leftNavChange() {
        //点击打开侧滑菜单
        if (!dl.isDrawerOpen(r1Left)) {
            dl.openDrawer(r1Left);
        } else if (dl.isDrawerOpen(r1Left)) {
            dl.closeDrawer(r1Left);
        }
    }

    /**
     * 切换Fragment
     *
     * @param from
     * @param to
     */
    public void switchContent(Fragment from, Fragment to) {
        otherFrameLayout.setVisibility(View.VISIBLE);
//        mapFrameLayout.setVisibility(View.GONE);
        if (from != to) {
            //from=to;
            mFragment = to;
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
            if (!to.isAdded()) {    // 先判断是否被add过
                if(to.equals(mapFragment))
                    transaction.hide(from).add(R.id.otherFrameLayout, to,"map").commit(); // 隐藏当前的fragment，add下一个到Activity中
                else
                    transaction.hide(from).add(R.id.otherFrameLayout, to).commit(); // 隐藏当前的fragment，add下一个到Activity中
            } else {
                transaction.hide(from).show(to).commit(); // 隐藏当前的fragment，显示下一个
            }
        }
    }

    /**
     * Activty回调接口
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1: {
                if (resultCode == 0) {//表示退出登录
                    Intent intent = new Intent(this, LoginActivity.class);
                    intent.putExtra("IsLogin", false);
                    startActivity(intent);
                    overridePendingTransition(0,R.anim.fade);
                    finish();
                }
            }break;
            case 11: {//个人信息界面
                if (resultCode == 11) {//表示有更新消息
                    String fileName = URL_FILEPATH + user.getMobilePhone() + ".png";
                    if (user.getHeadPicture() != null && !user.getHeadPicture().equals("")) {
                        String imgUrl = ApiUrl.URL_HOST + user.getHeadPicture();
                        mAppXUtilDao.GetHead(mHandler, imgUrl, fileName);
                        mDialog.show();
                    }
                } else if (resultCode == 12) {

                }
            }break;
        }
    }
    /**
     * 更新头像
     *
     * @param
     */
    private void updateImage() {
        String headName= FileUtil.getInstance().getImageName(user.getHeadPicture());
        String fileName = URL_FILEPATH +headName;
        if (FileUtil.fileIsExists(fileName)) {
            Uri uri = Uri.fromFile(new File(fileName));
            image_head.setImageURI(uri);
        } else if (user.getHeadPicture() != null && !user.getHeadPicture().equals("")) {
            String imgUrl = ApiUrl.URL_HOST + user.getHeadPicture();
            Picasso.with(MainActivity.this).load(imgUrl).placeholder(R.mipmap.defaultpicture).into(image_head);
        }
    }

    /**
     * 从本地获取用户名和Token用于获取个人信息
     */
    void doGetLocalStorage() {
        String id = LocalStorage.getString(MainActivity.this, "id").toString().trim();
        if (id != null && !id.equals("")) {
            user = LocalStorage.getUserModel(this);
            serverLogin(user.getMobilePhone(), user.getPassword());
            IMLogin(user.getMobilePhone(), user.getPassword());
        }
    }
    private void serverLogin(String mobilePhone, String password) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("mobilePhone", mobilePhone);
        map.put("password", password);
        mDialog.show();
        APIService.Post(ApiUrl.URL_GET_LOGIN, map, new RespCallBack<BaseBean<User>>(this) {
            @Override
            public void onSuccess(BaseBean<User> result) {
                super.onSuccess(result);
                if (result.success) {
                    user = result.data;
                    if (user != null && user.getId() != 0) {
                        myApplication.setIsLogin(true);
                        myApplication.setUser(user);
                        doLogin();
                        LocalLoginFinsh = true;
                        GetLogin();
                    } else {
                        myApplication.setIsLogin(false);
                        LocalLoginFinsh = false;
                        Toast(result.info);
                    }
                } else {
                    myApplication.setIsLogin(false);
                    LocalLoginFinsh = false;
                    Toast(result.info);
                }
            }
            @Override
            public void onFinished() {
                super.onFinished();
                mDialog.dismiss();
            }
        });
    }
    /**
     * IM账号登录
     *
     * @param userName
     * @param password
     */
    private void IMLogin(String userName, String password) {
        mDialog.show();
        try {
            EMClient.getInstance().login(userName, password, new EMCallBack() {//回调
                @Override
                public void onSuccess() {
                    EMClient.getInstance().groupManager().loadAllGroups();
                    EMClient.getInstance().chatManager().loadAllConversations();
                    IMLoginFinsh = true;
                    mHandler.sendEmptyMessage(ResultMessage.IMLOGIN_SUCCESS);
                }

                @Override
                public void onProgress(int progress, String status) {

                }

                @Override
                public void onError(int code, String message) {
                    Log.d("main", "登录聊天服务器失败！");
                    mHandler.obtainMessage(ResultMessage.IMLOGIN_FAILED, message);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.obtainMessage(ResultMessage.FAILED);
        }
    }

    /**
     * 显示pupWindow
     */
    private void pupwindowShow() {
        if (!isShowPup) {
            exitPopupWindow = new ExitPopupWindow(MainActivity.this);
            exitPopupWindow.setFocusable(true);
            exitPopupWindow.setBackgroundDrawable(new BitmapDrawable());
            exitPopupWindow.setOutsideTouchable(true);
            exitPopupWindow.setAnimationStyle(R.style.exit_menu_anim);
            // exitPopupWindow.showAsDropDown(mView.findViewById(R.id.activity_menu_title),0,18);
//            exitPopupWindow.showAtLocation(mView.findViewById(R.id.activity_menu_title),
//                    Gravity.BOTTOM | Gravity.END, 0, 0); // 设置layout在PopupWindow中显示的位置
            exitPopupWindow.showAtLocation(getLayoutInflater().inflate(R.layout.activity_main, null), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
            isShowPup = false;
            exitPopupWindow.setOnKeyboard1PopListener(new ExitPopupWindow.Keyboard1PopListener() {
                @Override
                public void onTimeSelect(String calendar) {
                    // TODO Auto-generated method stub
                    if (calendar != null) {
                        if (calendar.equals("1")) {
                            //t退出程序
                            MainActivity.this.finish();
                            overridePendingTransition(0,R.anim.fade);
                            android.os.Process.killProcess(android.os.Process.myPid());
                            System.exit(0);
                        } else if (calendar.equals("2")) {
                            //t退出账号
                            DoQuitLogin();
                            myApplication.setIsLogin(false);
                            myApplication.setUser(null);
                            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                            startActivity(intent);
                            overridePendingTransition(0,R.anim.fade);
                            MainActivity.this.finish();
                        } else if (calendar.equals("3")) {
                            //取消
                        }
                        if (exitPopupWindow != null) {
                            if (exitPopupWindow.isShowing()) {
                                exitPopupWindow.dismiss();
                                isShowPup = false;
                            }
                        }
                    }
                }
            });
            exitPopupWindow.setOnKeyboard1IsPupListener(new ExitPopupWindow.Keyboard1isPupListener() {

                @Override
                public void onIsPup(Boolean isPup) {
                    // TODO Auto-generated method stub
                    isShowPup = !isPup;
                }
            });

        }
    }

    /**
     * 退出登录
     */
    private void DoQuitLogin() {
        LocalStorage.saveString(MainActivity.this, "id",
                String.valueOf(""));
        LocalStorage.removeUserModel(MainActivity.this);
    }

    /**
     * 缓存登录数据在本地用于进入自动登录
     */
    void doLogin() {
        LocalStorage.saveString(MainActivity.this, "id", String.valueOf(user.getId()));
        LocalStorage.saveUserModel(MainActivity.this, user);
    }

    private void setData() {
        user = myApplication.getUser();
        if(user == null){
            return;
        }
        if (user.getNickName() != null && !user.getNickName().equals("null")) {
            text_nickName.setText("" + user.getNickName());
        }else{
            text_nickName.setText("昵称");
        }
        if (user.getIndividualSignature() != null && !user.getIndividualSignature().equals("null")) {
            text_individualSignature.setText("" + user.getIndividualSignature());
        }
        updateImage();
    }

    /**
     * 开始登录跳转
     */
    private void GetLogin() {
        if (IMLoginFinsh && LocalLoginFinsh) {
            mDialog.dismiss();
            if (myApplication.isLogin()) {
                setData();
            }
        }
    }

    /**
     * 重写后退函数
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            pupwindowShow();
            return true;
        } else
            return super.onKeyDown(keyCode, event);
    }
}
